<template>
  <div class="app-container">
    <el-form label-position="left" label-width="10rem">
      <el-form-item label="上传海报/选择套餐:">
        <el-switch
          v-model="carouselInfo.type"
          active-text="选择套餐"
          inactive-text="上传海报"
          active-value="1"
          inactive-value="0"
          disabled
        ></el-switch>
      </el-form-item>
      <el-form-item label="上传图片:">
        <el-upload
          drag
          :on-success="onUploadPosterSuccess"
          :before-upload="beforeUpload"
          :on-preview="onUploadPreview"
          :on-remove="onUploadPosterRemove"
          :multiple="false"
          :action="BASE_API + '/admin/show/fileUpload'"
          class="upload-demo"
          list-type="picture"
          :file-list="fileImgList"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">
            只能上传jpg/png/gif文件，且不超过2MB
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="备注信息:">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="carouselInfo.remark"
          maxlength="100"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item label="排序:">
        <el-input-number v-model="carouselInfo.sort" :min="1"></el-input-number>
      </el-form-item>

      <el-form-item label="是否使用:">
        <el-switch
          v-model="carouselInfo.publishStatus"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-value="1"
          inactive-value="0"
        ></el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">保存</el-button>
        <el-button @click="back">返回</el-button>
      </el-form-item>
    </el-form>

    <!--图片预览-->
    <el-dialog :visible.sync="dialogImageVisible">
      <img :src="dialogImageUrl" width="100%" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import carouselInfoApi from '@/api/show/carouselInfo'

const defaultForm = {
  id: '',
  type: 0,
  sort: '',
  imgUrl: '',
  publishStatus: 0,
  remark: ''
}

export default {
  data() {
    return {
      // 接口API地址
      BASE_API: 'http://localhost:9000',

      carouselInfo: defaultForm,
      saveBtnDisabled: false,
      fileImgList: [],
      // 图片预览区域url
      dialogImageUrl: '',
      // 图片预览对话框
      dialogImageVisible: false
    }
  },

  // 监听器
  watch: {
    $route(to, from) {
      console.log('路由变化......')
      console.log(to)
      console.log(from)
      this.init()
    }
  },

  // 生命周期方法（在路由切换，组件不变的情况下不会被调用）
  created() {
    console.log('form created ......')
    this.init()
  },

  methods: {
    // 表单初始化
    init() {
      // debugger
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id
        this.fetchDataById(id)
      } else {
        // 对象拓展运算符：拷贝对象，而不是赋值对象的引用
        this.carouselInfo = { ...defaultForm }
      }
    },
    saveOrUpdate() {
      // this.saveBtnDisabled = true // 防止表单重复提交
      if (!this.carouselInfo.id) {
        this.saveData()
      } else {
        this.updateData()
      }
    },

    // 新增
    saveData() {
      console.log(this.carouselInfo)
      carouselInfoApi.save(this.carouselInfo).then((response) => {
        if (response.code) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/show/carouselInfo/list' })
          this.saveBtnDisabled = false
        }
      })
    },

    // 根据id更新记录
    updateData() {
      carouselInfoApi.updateById(this.carouselInfo).then((response) => {
        if (response.code) {
          this.$message({
            type: 'success',
            message: response.message
          })
          this.$router.push({ path: '/show/carouselInfo/list' })
          this.saveBtnDisabled = false
        }
      })
    },

    back() {
      this.$router.push({ path: '/show/carouselInfo/list' })
    },

    // 根据id查询记录
    fetchDataById(id) {
      carouselInfoApi.getById(id).then((response) => {
        this.carouselInfo = response.data
        let obj = new Object()
        obj.url = this.carouselInfo.imgUrl
        // 填充上传文件列表
        this.fileImgList.push(obj)
      })
    },

    // 文件上传限制条件
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 5

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG、PNG 或 GIF 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 5MB!')
        return false
      }
      return true
    },

    // 上传的文件预览
    onUploadPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },

    // 上传图片成功的回调
    onUploadPosterSuccess(file) {
      this.fileImgList = []
      console.log(file)
      let obj = new Object()
      obj.url = file.data
      // 填充上传文件列表
      this.fileImgList.push(obj)
      // 填充上传文件列表
      this.carouselInfo.imgUrl = file.data
    },

    // 删除上传的文件
    onUploadPosterRemove() {
      this.fileImgList = []
      this.carouselInfo.imgUrl = null
    }
  }
}
</script>
<style scoped>
.littleMarginTop {
  margin-top: 10px;
}

.paramInput {
  width: 250px;
}

.paramInputLabel {
  display: inline-block;
  width: 100px;
  text-align: right;
  padding-right: 10px;
}

.cardBg {
  background: #f8f9fc;
}
</style>
